<template>
  <div class="order-container">
    <h1 class="page-title">我的订单</h1>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>正在加载订单数据...</p>
    </div>

    <!-- 空状态 -->
    <div v-else-if="orders.length === 0" class="empty-container">
      <div class="empty-icon">📋</div>
      <p>暂无订单数据</p>
      <button @click="loadOrders" class="retry-btn">重新加载</button>
    </div>
    
    <div v-else class="order-list">
      <div 
        v-for="order in orders" 
        :key="order.id || 'unknown'"
        class="order-card"
        :class="{
          'expanded': expandedOrder === order.id,
          'status-pending': order.status === 'pending',
          'status-delivering': order.status === 'delivering',
          'status-completed': order.status === 'completed'
        }"
        @click="toggleExpand(order.id)"
      >
        <div class="order-header">
          <div class="order-meta">
            <span class="order-id">订单号: {{ order.id }}</span>
            <span class="order-time">{{ formatTime(order.createTime) }}</span>
          </div>
          <div class="order-status">
            <span>{{ statusText(order.status) }}</span>
          </div>
        </div>
        
        <div class="order-summary">
          <div class="shop-info">
            <div class="shop-name">{{ order.shopName }}</div>
            <div class="shop-address">{{ order.shopAddress }}</div>
          </div>
          <div class="price-info">
            <span class="total-price">¥{{ (order.actualPayment || 0).toFixed(2) }}</span>
          </div>
        </div>
        
        <transition name="expand">
          <div v-show="expandedOrder === order.id" class="order-details">
            <div class="section">
              <h3 class="section-title">商品信息</h3>
              <div v-for="item in order.orderItems || []" :key="item.id || 'unknown'" class="item">
                <div class="item-info">
                  <span class="item-name">{{ item.goodsName }}</span>
                  <span class="item-quantity">x{{ item.quantity }}</span>
                </div>
                <div class="item-price">¥{{ (item.subtotal || 0).toFixed(2) }}</div>
              </div>
            </div>
            
            <div class="price-details">
              <div class="price-row">
                <span>商品总价</span>
                <span>¥{{ (order.totalAmount || 0).toFixed(2) }}</span>
              </div>
              <div class="price-row discount">
                <span>优惠减免</span>
                <span>-¥{{ (order.discount || 0).toFixed(2) }}</span>
              </div>
              <div class="price-row total">
                <span>实付金额</span>
                <span class="actual-payment">¥{{ (order.actualPayment || 0).toFixed(2) }}</span>
              </div>
            </div>
            
            <div class="section">
              <h3 class="section-title">配送信息</h3>
              <div class="address-row">
                <div class="address-label">商家地址</div>
                <div class="address-content">{{ order.shopAddress }}</div>
              </div>
              <div class="address-row">
                <div class="address-label">用户地址</div>
                <div class="address-content">{{ order.userAddress }}</div>
              </div>
              <div class="rider-info" v-if="order.riderName">
                <div class="rider-avatar">
                  <img :src="order.riderAvatar || '/boy.png'" alt="骑手头像">
                </div>
                <div class="rider-details">
                  <div class="rider-name">{{ order.riderName }} <span class="rider-rating">⭐ {{ order.riderRating || 4.5 }}</span></div>
                  <div class="rider-phone">电话: {{ order.riderPhone || '138****1234' }}</div>
                </div>
              </div>
            </div>
            
            <div class="action-buttons" v-if="order.status !== 'completed'">
              <button 
                v-if="order.status === 'pending'" 
                class="btn confirm-btn"
                @click.stop="confirmOrder(order.id)"
                :disabled="updating"
              >
                {{ updating ? '处理中...' : '确认接单' }}
              </button>
              <button 
                v-if="order.status === 'delivering'" 
                class="btn complete-btn"
                @click.stop="completeOrder(order.id)"
                :disabled="updating"
              >
                {{ updating ? '处理中...' : '确认送达' }}
              </button>
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useUserIdStore } from '@/stores/UserId';
import { 
  selectByUserId, 
  getOrderDetail, 
  updateStatus, 
  OrderStatus,
  type Order,
  type OrderItem 
} from '@/http/Order';
import { message } from '@/utils/message';

// 原静态数据接口（保留备用）
// interface OrderItem {
//   id: string;
//   name: string;
//   price: number;
//   quantity: number;
// }

// interface Rider {
//   id: string;
//   name: string;
//   phone: string;
//   rating: number;
//   avatar: string;
// }

// interface Order {
//   id: string;
//   shopName: string;
//   shopAddress: string;
//   userAddress: string;
//   time: string;
//   status: 'pending' | 'delivering' | 'completed';
//   totalAmount: number;
//   discount: number;
//   actualPayment: number;
//   items: OrderItem[];
//   rider?: Rider;
// }

const userIdStore = useUserIdStore();
const expandedOrder = ref<number | null>(null);
const loading = ref(true);
const updating = ref(false);

// 使用后端数据类型
const orders = ref<Order[]>([]);

// 原静态数据（保留备用）
// const staticOrders = ref<Order[]>([
//   {
//     id: 'ORD202306051234',
//     shopName: '美味中餐厅',
//     shopAddress: '朝阳区建国路88号',
//     userAddress: '海淀区中关村大街1号科技大厦A座',
//     time: '2023-06-05 12:34',
//     status: 'pending',
//     totalAmount: 98.5,
//     discount: 15.0,
//     actualPayment: 83.5,
//     items: [
//       { id: '1', name: '宫保鸡丁', price: 42.0, quantity: 1 },
//       { id: '2', name: '麻婆豆腐', price: 36.0, quantity: 1 },
//       { id: '3', name: '米饭', price: 3.0, quantity: 2 },
//       { id: '4', name: '酸辣汤', price: 17.5, quantity: 1 },
//     ]
//   },
//   {
//     id: 'ORD202306041521',
//     shopName: '披萨之家',
//     shopAddress: '东城区王府井大街66号',
//     userAddress: '西城区金融街甲9号',
//     time: '2023-06-04 15:21',
//     status: 'delivering',
//     totalAmount: 128.0,
//     discount: 20.0,
//     actualPayment: 108.0,
//     items: [
//       { id: '5', name: '超级至尊披萨', price: 89.0, quantity: 1 },
//       { id: '6', name: '香辣鸡翅', price: 32.0, quantity: 1 },
//       { id: '7', name: '可乐', price: 7.0, quantity: 1 },
//     ],
//     rider: {
//       id: 'R1001',
//       name: '张师傅',
//       phone: '138****1234',
//       rating: 4.8,
//       avatar: '/boy.png'
//     }
//   },
//   {
//     id: 'ORD202306031845',
//     shopName: '轻食沙拉',
//     shopAddress: '海淀区学院路18号',
//     userAddress: '朝阳区三里屯SOHO B座',
//     time: '2023-06-03 18:45',
//     status: 'completed',
//     totalAmount: 65.0,
//     discount: 10.0,
//     actualPayment: 55.0,
//     items: [
//       { id: '8', name: '牛油果鸡肉沙拉', price: 38.0, quantity: 1 },
//       { id: '9', name: '鲜榨橙汁', price: 22.0, quantity: 1 },
//       { id: '10', name: '全麦面包', price: 5.0, quantity: 1 },
//     ],
//     rider: {
//       id: 'R1002',
//       name: '李女士',
//       phone: '139****5678',
//       rating: 4.9,
//       avatar: '/girl.png'
//     }
//   }
// ]);

// 加载订单数据
const loadOrders = async () => {
  loading.value = true;
  try {
    console.log('🚀 开始加载订单数据...');
    
    if (!userIdStore.currentUserId) {
      console.log('⚠️ 用户未登录，使用静态数据');
      // orders.value = staticOrders.value;
      message.warning('请先登录');
      return;
    }

    // 获取用户订单数据
    const response = await selectByUserId(userIdStore.currentUserId, 1, 50);
    
    if (response.data && response.data.list) {
      console.log('✅ 订单数据加载成功:', response.data.list.length, '个订单');
      
      // 为每个订单获取详细信息（包含订单项）
      const ordersWithDetails = await Promise.all(
        response.data.list.map(async (order) => {
          try {
            const detailResponse = await getOrderDetail(order.id!);
            return detailResponse.data;
          } catch (error) {
            console.warn('获取订单详情失败:', order.id, error);
            return order; // 返回基本订单信息
          }
        })
      );
      
      orders.value = ordersWithDetails;
      console.log('📊 订单详情数据:', ordersWithDetails);
    } else {
      console.log('⚠️ 没有订单数据');
      orders.value = [];
      message.info('暂无订单数据');
    }
  } catch (error: any) {
    console.error('❌ 加载订单数据失败:', error);
    
    if (error.message) {
      message.error(`加载订单数据失败: ${error.message}`);
    } else {
      message.error('加载订单数据失败，请检查网络连接');
    }
    
    // 错误时可以使用静态数据作为备用
    // orders.value = staticOrders.value;
  } finally {
    loading.value = false;
  }
};

const toggleExpand = (orderId: number | null) => {
  expandedOrder.value = expandedOrder.value === orderId ? null : orderId;
};

const statusText = (status: string | null) => {
  const statusMap: Record<string, string> = {
    'pending': '待接单',
    'confirmed': '已接单',
    'preparing': '准备中',
    'delivering': '配送中',
    'completed': '已完成',
    'cancelled': '已取消'
  };
  return statusMap[status || ''] || status || '未知状态';
};

const confirmOrder = async (orderId: number | null) => {
  if (!orderId) return;
  
  updating.value = true;
  try {
    console.log('🔄 确认接单:', orderId);
    
    await updateStatus(orderId, OrderStatus.CONFIRMED);
    
    // 更新本地订单状态
  const order = orders.value.find(o => o.id === orderId);
  if (order) {
      order.status = OrderStatus.CONFIRMED;
      // 模拟分配骑手信息
      order.riderName = ['张', '王', '李', '赵'][Math.floor(Math.random() * 4)] + '师傅';
      order.riderPhone = '138****' + Math.floor(1000 + Math.random() * 9000);
      order.riderRating = 4.5 + Math.random() * 0.4;
      order.riderAvatar = '/boy.png';
    }
    
    message.success('订单已确认接单');
    console.log('✅ 订单状态更新成功');
  } catch (error: any) {
    console.error('❌ 确认接单失败:', error);
    message.error('确认接单失败: ' + (error.message || '网络错误'));
  } finally {
    updating.value = false;
  }
};

const completeOrder = async (orderId: number | null) => {
  if (!orderId) return;
  
  updating.value = true;
  try {
    console.log('🔄 确认送达:', orderId);
    
    await updateStatus(orderId, OrderStatus.COMPLETED);
    
    // 更新本地订单状态
  const order = orders.value.find(o => o.id === orderId);
  if (order) {
      order.status = OrderStatus.COMPLETED;
    }
    
    message.success('订单已确认送达');
    console.log('✅ 订单状态更新成功');
  } catch (error: any) {
    console.error('❌ 确认送达失败:', error);
    message.error('确认送达失败: ' + (error.message || '网络错误'));
  } finally {
    updating.value = false;
  }
};

// 格式化时间
const formatTime = (timeString: string | null) => {
  if (!timeString) return '';
  
  try {
    const date = new Date(timeString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return timeString;
  }
};

// 页面加载时获取数据
onMounted(() => {
  loadOrders();
});
</script>

<style scoped>
.order-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  padding: 20px 20px 80px 20px;
  min-height: 100vh;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
  box-sizing: border-box;
}

.page-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 28px;
  font-weight: 600;
  position: relative;
}

.page-title::after {
  content: '';
  display: block;
  width: 60px;
  height: 4px;
  background: linear-gradient(90deg, #ff6b6b, #ff8e53);
  margin: 10px auto 0;
  border-radius: 2px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  border-left: 5px solid #ff6b6b;
}

.order-card.status-pending {
  border-left-color: #ff9f43;
}

.order-card.status-delivering {
  border-left-color: #2e86de;
}

.order-card.status-completed {
  border-left-color: #10ac84;
}

.order-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 20px rgba(0, 0, 0, 0.12);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 24px;
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.order-meta {
  display: flex;
  flex-direction: column;
}

.order-id {
  font-weight: 600;
  color: #343a40;
  font-size: 16px;
}

.order-time {
  color: #6c757d;
  font-size: 14px;
  margin-top: 4px;
}

.order-status {
  font-weight: 600;
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 14px;
}

.status-pending .order-status {
  background-color: #fff3e0;
  color: #ff9f43;
}

.status-delivering .order-status {
  background-color: #e3f2fd;
  color: #2e86de;
}

.status-completed .order-status {
  background-color: #e8f5e9;
  color: #10ac84;
}

.order-summary {
  display: flex;
  justify-content: space-between;
  padding: 20px 24px;
  align-items: center;
}

.shop-info {
  flex: 1;
}

.shop-name {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 6px;
}

.shop-address {
  color: #6c757d;
  font-size: 14px;
}

.price-info {
  font-size: 20px;
  font-weight: 700;
  color: #ff6b6b;
}

.order-details {
  padding: 0 24px 24px;
  border-top: 1px solid #f1f3f5;
}

.section {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #495057;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #e9ecef;
}

.item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f8f9fa;
}

.item-info {
  display: flex;
  gap: 10px;
}

.item-name {
  color: #343a40;
}

.item-quantity {
  color: #6c757d;
}

.item-price {
  font-weight: 600;
  color: #495057;
}

.price-details {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 16px;
  margin-top: 20px;
}

.price-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  font-size: 15px;
}

.discount {
  color: #10ac84;
}

.total {
  border-top: 1px solid #e9ecef;
  margin-top: 8px;
  padding-top: 12px;
  font-weight: 700;
  font-size: 18px;
}

.actual-payment {
  color: #ff6b6b;
}

.address-row {
  display: flex;
  margin-bottom: 12px;
}

.address-label {
  font-weight: 600;
  color: #495057;
  min-width: 80px;
}

.address-content {
  color: #6c757d;
  flex: 1;
}

.rider-info {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 14px;
  margin-top: 15px;
}

.rider-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 15px;
}

.rider-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.rider-details {
  flex: 1;
}

.rider-name {
  font-weight: 600;
  color: #343a40;
  margin-bottom: 4px;
}

.rider-rating {
  color: #ff9f43;
  font-size: 14px;
}

.rider-phone {
  color: #6c757d;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 25px;
}

.btn {
  padding: 12px 28px;
  border-radius: 30px;
  font-weight: 600;
  font-size: 16px;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
  outline: none;
}

.confirm-btn {
  background: linear-gradient(135deg, #ff9f43, #ff6b6b);
  color: white;
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.complete-btn {
  background: linear-gradient(135deg, #2e86de, #10ac84);
  color: white;
  box-shadow: 0 4px 12px rgba(16, 172, 132, 0.3);
}

.btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
}

.expand-enter-active, .expand-leave-active {
  transition: all 0.4s ease;
  max-height: 1000px;
  overflow: hidden;
}

.expand-enter-from, .expand-leave-to {
  max-height: 0;
  opacity: 0;
  padding-top: 0;
  padding-bottom: 0;
}

@media (max-width: 600px) {
  .order-container {
    padding: 15px 15px 70px 15px;
    min-height: calc(100vh - 56px);
  }
  
  .order-header, .order-summary {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .order-status {
    align-self: flex-start;
  }
  
  .action-buttons {
    justify-content: center;
  }
  
  .btn {
    width: 100%;
    padding: 14px;
  }
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #ff6b6b;
  border-top: 4px solid transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-container p {
  color: #6c757d;
  font-size: 16px;
  margin: 0;
}

/* 空状态样式 */
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-container p {
  color: #6c757d;
  font-size: 16px;
  margin: 0 0 20px 0;
}

.retry-btn {
  padding: 12px 24px;
  background: linear-gradient(135deg, #ff6b6b, #ff8e53);
  color: white;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s ease;
  outline: none;
}

.retry-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(255, 107, 107, 0.3);
}

/* 按钮禁用状态 */
.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}

.btn:disabled:hover {
  transform: none !important;
  box-shadow: none !important;
}
</style>